﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FTchina;
using System.Data;
using System.Collections;
using System.Text.RegularExpressions;
using System.IO;

public partial class UI_usermanage : System.Web.UI.Page
{
    ArrayList ayl = new ArrayList();//存放要删除的菜单的id

    string action = "";//list:列表 del:删除 mod:修改

    protected void Page_Load(object sender, EventArgs e)
    {
        basic.CheckAdmin(this);
        basic.ChkPoewr(this, FTchina.Api.htmlpath.GetCurrentPagePath());
        action = basic.FilterSQL(Request["action"]);
        if (action.Length == 0) action = "list";
        if (!IsPostBack)
        {

            switch (action)
            {
                case "del": Delete(); break;
                case "mod": modify(); break;
            }
            plrootadd.Visible = true;

            LoadList();
        }

    }

    private void modify()
    {
        plmodi.Visible = true;
        DataTable dt = shujuku.GetDataTable("select * from userlist where id=" + basic.FilterSQL(Request["id"]));

        txbyname.Text = dt.Rows[0]["master_name"].ToString();
        txbpx.Text = dt.Rows[0]["paixu"].ToString();
        txbUrl.Text = dt.Rows[0]["touxiang"].ToString();

    }



    private void Delete()
    {
        string id = basic.FilterSQL(Request["id"]);
        if (id.Length == 0) { JS.Alert("不允许的操作！"); return; }
        ayl.Clear();
        //获取ID值
        GetAllId(id, 0);
        //删除分类条目
        DeleteFenleiID();

    }


    #region 加载分类



    /// <summary>
    /// 加载整个分类表
    /// </summary>
    private void LoadList()
    {

        litlist.Text = "";
        ddllm.Items.Clear();
        ddlold.Items.Clear();
        ddlnew.Items.Clear();
        int MTcount = 0;//执行遍历的次数
        //开始迭代加载
        MakeTr("0", MTcount);




    }
    /// <summary>
    /// 装配每一行
    /// </summary>
    /// <param name="id">上级ID</param>
    /// <param name="count">迭代次数</param>
    private void MakeTr(string id, int count)
    {

        DataView dv = new DataView(shujuku.GetDataTable("select * from userlist where parentid=" + id + " order by paixu desc,id desc"));

        string shanchu = string.Empty;//设置自定义表单不能删除


        foreach (DataRowView drv in dv)
        {
            // shanchu = (drv["master_name"].ToString() == "自定义表单") ? "" : "删除";//设置自定义表单不能删除
            shanchu = "删除";
            //形成表格
            litlist.Text += "<tr><td>" + MakeFelgefu(count) + drv["master_name"].ToString() + "</td><td>" + drv["paixu"].ToString() + "</td><td> <a href=del.aspx?T=userlist&id=" + drv["id"].ToString() + "><a href='?action=mod&id=" + drv["id"] + "' >修改</a> <a href='?action=del&id=" + drv["id"] + "' title='header=[删除说明] body=[被删除项如果包含子项，那么所有的子项也将被删除]'>" + shanchu + "</a></td></tr>";

            //形成下拉列表
            ListItem li = new ListItem(MakeFelgefu(count) + drv["master_name"].ToString(), drv["id"].ToString());
            ddllm.Items.Add(li);
            ddlnew.Items.Add(li);
            ddlold.Items.Add(li);
            //再次遍历
            MakeTr(drv["id"].ToString(), count + 1);

        }

    }
    /// <summary>
    /// Make分隔符
    /// </summary>
    /// <param name="count"></param>
    /// <returns></returns>
    private string MakeFelgefu(int count)
    {
        string Returnwords = string.Empty;
        if (count == 0)
        {
            Returnwords = "";
        }

        else
        {
            Returnwords = ("├").PadLeft(count, '　');
        }
        return Returnwords;
    }

    #endregion

    #region 删除分类

    /// <summary>
    /// 获取系统要删除的对象的ID列表
    /// </summary>
    /// <param name="id"></param>
    private void GetAllId(string id, int count)
    {
        if (count == 0) { ayl.Add(id); }//第一次循环
        DataView dv = new DataView(shujuku.GetDataTable("select * from userlist where parentid=" + id + " order by id asc"));
        foreach (DataRowView drv in dv)
        {
            ayl.Add(drv["id"].ToString());
            GetAllId(drv["id"].ToString(), count + 1);
        }

    }
    /// <summary>
    /// 将ArrayList中的值转换为sql中的值
    /// </summary>
    /// <param name="aly"></param>
    /// <returns></returns>
    private string ArrayList2String(ArrayList aly)
    {
        string ReturnWords = "";
        foreach (string item in aly)
        {
            ReturnWords += item + ",";
        }
        ReturnWords = ReturnWords.Substring(0, ReturnWords.Length - 1);
        return ReturnWords;
    }

    private void DeleteFenleiID()
    {
        string sql = "delete from userlist where id in (" + ArrayList2String(ayl) + ")";
        // Response.Write(sql);
        shujuku.ExecuteSql(sql);
        LoadList();
    }
    #endregion


    #region 按钮行为
    protected void btnziok_Click(object sender, EventArgs e)
    {
        string parentid = ddllm.SelectedValue.ToString();
        string master_name = basic.FilterSQL(txbzifl.Text);
        if (CheckSameName(master_name)) { JS.Alert("已有同名项"); LoadList(); return; }

        string sql = "insert into userlist (parentid,master_name) values(" + parentid + ",'" + master_name + "') ";
        UImsg.PageRender(shujuku.ExecuteSql(sql));

    }
    protected void btnroot_Click(object sender, EventArgs e)
    {
        string master_name = basic.FilterSQL(txbroot.Text);
        if (CheckSameName(master_name)) { JS.Alert("已有同名项"); LoadList(); return; }
        string sql = "insert into userlist (parentid,master_name) values('0','" + master_name + "') ";
        UImsg.PageRender(shujuku.ExecuteSql(sql));

    }
    protected void btnmodok_Click(object sender, EventArgs e)
    {
        string master_name = basic.FilterSQL(txbyname.Text);
        string id = basic.FilterSQL(Request["id"]);
        string paixu = basic.FilterSQL(txbpx.Text);
        string touxiang = basic.SafeRequest(txbUrl.Text);
        if (paixu.Length == 0) paixu = "0";
        if (master_name != GetNameByID(id))
        {
            if (CheckSameName(master_name)) { JS.Alert("已有同名项"); LoadList(); return; }
        }

        //验证数据
        if (id.Length == 0 || master_name.Length == 0) { JS.Alert("请输入完整！"); return; }
        string sql = "update userlist set touxiang='" + touxiang + "',paixu=" + paixu + ",master_name='" + master_name + "' where id=" + id;

        UImsg.PageRender(shujuku.ExecuteSql(sql));

    }
    #endregion
    protected void btnmove_Click(object sender, EventArgs e)
    {
        string old = ddlold.SelectedValue;
        string newfenle = ddlnew.SelectedValue;
        string sql = "update userlist set parentid=" + newfenle + " where id=" + old;
        // UImsg.PageRender(shujuku.ExecuteSql(sql));
    }

    /// <summary>
    /// 检查是否根菜单
    /// </summary>
    /// <returns></returns>
    protected Boolean CheckRoot()
    {
        return !shujuku.testread("select id from userlist where parentid=0");
    }
    /// <summary>
    /// 通过ID获取用户名
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    protected String GetNameByID(string id)
    {
        return shujuku.GetDataTable("select master_name from userlist where id='" + id + "'").Rows[0][0].ToString();
    }

    /// <summary>
    /// 检查是否有同名的
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    protected Boolean CheckSameName(string name)
    {
        string testsql = "select * from userlist where master_name='{0}'";
        basic.Log(string.Format(testsql, name));
        return shujuku.testread(string.Format(testsql, name));
    }



    #region 上传
    protected void btnupok_Click(object sender, EventArgs e)
    {
        if (!fudoc.HasFile) { JS.Alert("请选择一个图像！"); return; }
        if (!(fudoc.FileName.ToLower().Contains(".jpg") || fudoc.FileName.ToLower().Contains(".bmp") || fudoc.FileName.ToLower().Contains(".png") || fudoc.FileName.ToLower().Contains(".gif"))) { JS.Alert("请选择一个图像文件！"); return; }

        //创建相应的分类目录
        string path = "touxiang";
        string RealPath = Server.MapPath("~/uploads/" + path + "/");
        JS.Alert(RealPath);

        if (!Directory.Exists(RealPath)) Directory.CreateDirectory(RealPath);//创建目录


        string filename = basic.GetGuid();
        int indexhz = fudoc.FileName.LastIndexOf(".");
        string houzhui = fudoc.FileName.Substring(indexhz, fudoc.FileName.Length - indexhz).ToLower();
        string newfilename = filename + houzhui;

        if (File.Exists(RealPath + newfilename)) { JS.Alert("指定类别下已存在同名文件！请重命名您要上传的文件！以确保不会重名！"); return; }

        try
        {

            fudoc.SaveAs(RealPath + newfilename);
            txbUrl.Text = "uploads/" + path + "/" + newfilename;
            // shujuku.ExecuteSql("insert into files ( path ) values ('" + txbUrl.Text + "')");

            JS.Alert("上传成功！");
        }
        catch (System.Exception error) { LogNet.LogBLL.error("上传失败！管理员可能有用的信息：" + error.Message); }

    }

    #endregion
}
